package com.nuo.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.nuo.hibernate.entity.User;



public class UserProvide {
	
	public static int index;
	
	public List<User> getAllUser(){
		List<User> list = new ArrayList<User>();
		Connection con = null;
		PreparedStatement ps = null;
		try {
			String sql = "select * from test_user";
			con = ConnectionManager.getConnection();
			ps = con.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			while(rs.next()){
				User user = new User();
				user.setId(rs.getInt("id"));
				user.setName(rs.getString("name"));
				user.setUpdateDate(rs.getTimestamp("updateDate"));
				list.add(user);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			try {
				if(con != null){con.close();}
				if(ps != null){ps.close();}
			} catch (SQLException e) {
				System.out.println("关闭连接错误");
				e.printStackTrace();
			}
		}
		return list;
	}
	
	public boolean saveOrUpdate(User user){
		Connection con = null;
		PreparedStatement ps = null;
		try {
			if(user.getId() == null){//新增
				String sql = "insert into test_user values (?, ?, ?)";
				con = ConnectionManager.getConnection();
				ps = con.prepareStatement(sql);
				ps.setInt(1, index++);
				ps.setString(2, user.getName());
				ps.setTimestamp(3, user.getUpdateDate());
				
				return ps.execute();
			}else{//更新
				String sql = "update test_user set name=?, updateDate=? where id=?";
				con = ConnectionManager.getConnection();
				ps = con.prepareStatement(sql);
				ps.setString(1, user.getName());
				ps.setTimestamp(2, user.getUpdateDate());
				ps.setInt(3, user.getId());
				
				return ps.execute();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		} finally{
			try {
				if(con != null){con.close();}
				if(ps != null){ps.close();}
			} catch (SQLException e) {
				System.out.println("关闭连接错误");
				e.printStackTrace();
			}
		}
		
	}
}
